﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using HodhodNews;
using Googler.BLL;

namespace Googler.Web
{
    public partial class AppMonitor : System.Web.UI.Page
    {

        protected class AppStatistics
        {
            public string Text { get; set; }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Refresh();
            }
        }

        protected void btnRefresh_Click(object sender, EventArgs e)
        {
            Refresh();

        }

        private void Refresh()
        {
            List<AppStatistics> list = new List<AppStatistics>();
            list.Add(new AppStatistics()
            {
                Text = "Application is continuously running from :" + Global.AppStartedAt.ToHumman()
            });

            if (File.Exists(Consts.AggregationLogFilePath))
            {
                var aggregationStatistics = GetAppStatisticsFromLogFile(Consts.AggregationLogFilePath);
                list.Add(aggregationStatistics);
            }

            if (File.Exists(Consts.SimulationServiceLogFilePath))
            {
                var simulationStatistics = GetAppStatisticsFromLogFile(Consts.SimulationServiceLogFilePath);
                list.Add(simulationStatistics);
            }


            foreach (var tl in Sessions.NotificationMessages)
            {
                list.Add(new AppStatistics()
                {
                    Text = tl.ToString()
                });
            }

            rptStatistics.DataSource = list;
            rptStatistics.DataBind();

        }
        AppStatistics GetAppStatisticsFromLogFile(string path)
        {
            using (StreamReader reader = new StreamReader(path, true))
            {
                string line = reader.ReadLine();
                int counter = 0;
                while (!string.IsNullOrWhiteSpace(line))
                {
                    line = reader.ReadLine();
                }
                if (line != null)
                {
                    var lineParts = line.Split(':');
                    return new AppStatistics()
                    {
                        Text = lineParts[0] + Convert.ToDateTime(lineParts[1]).ToHumman()
                    };
                }
                return new AppStatistics() { Text = "" };
            }
        }
    }
}